package com.yupi.yuaicodemother.ai.model;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
//import org.apache.poi.xwpf.usermodel.*;


@Component
public class FileTextExtractor {

    public String extract(MultipartFile file) throws IOException {
        String name = file.getOriginalFilename();
        if (name == null) throw new IllegalArgumentException("文件名不能为空");

        String lower = name.toLowerCase();

        try {
            if (lower.endsWith(".txt") || lower.endsWith(".md")) {
                return new String(file.getBytes(), StandardCharsets.UTF_8);
            }

            if (lower.endsWith(".docx")) {
                try (XWPFDocument doc = new XWPFDocument(file.getInputStream())) {
                    return doc.getParagraphs()
                            .stream()
                            .map(XWPFParagraph::getText)
                            .collect(Collectors.joining("\n"));
                }
            }

            if (lower.endsWith(".doc")) {
                // 使用 POI-HWPF 解析 .doc
                try (HWPFDocument doc = new HWPFDocument(file.getInputStream())) {
                    return doc.getDocumentText();
                }
            }

            if (lower.endsWith(".pdf")) {
                try (PDDocument pdf = PDDocument.load(file.getInputStream())) {
                    PDFTextStripper stripper = new PDFTextStripper();
                    return stripper.getText(pdf);
                }
            }

            throw new IllegalArgumentException("不支持的文件类型");
        } catch (Exception e) {
            throw new IOException("文件解析失败: " + e.getMessage(), e);
        }
    }


    /**
     * 从纯文本内容中识别“共 N 页”或“共 {} 页”格式的数字
     * 若未命中，默认返回 1
     */
    public int extractPageCount(String text) {
        if (text == null) return 1;
        // 匹配“共 5 页”或“共5页”或“共 {} 页”
        java.util.regex.Matcher m =
                java.util.regex.Pattern.compile("共\\s*(?:\\{)?(\\d+)(?:\\})?\\s*页")
                        .matcher(text);
        return m.find() ? Integer.parseInt(m.group(1)) : 1;
    }
}